import { login, logout, info } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, arrayToRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userId: null,
    username: '',
    phone: '',
    avatar: '',
    menus: [],
    leftMenus: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_NAME: (state, name) => {
    state.username = name
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_LEFT_MENUS: (state, menus) => {
    state.leftMenus = menus
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, mode } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone: username.trim(), secret: password, mode: mode }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.authorization)
        setToken(data.authorization, data.cookie)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      info(null).then(response => {
        const { data } = response
        if (data) {
          const { user_id, phone, name, avatar, group } = data
          commit('SET_USER_ID', user_id)
          commit('SET_NAME', name)
          commit('SET_PHONE', phone)
          commit('SET_AVATAR', avatar)
          if (group && group.menus) {
            commit('SET_MENUS', arrayToRouter(group.menus))
          }
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')

        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

